import './.env';
import Koa from 'koa';
import cross from 'koa2-cors';
import dayjs from 'dayjs';
import koaBody from 'koa-body';
import utc from 'dayjs/plugin/utc';
import { createServer } from 'http';
import timezone from 'dayjs/plugin/timezone';
import relativeTime from 'dayjs/plugin/relativeTime';
import { dbConnect } from './database/connect';
import { apiRouter, allRoutes } from './routes';
import { errorMiddleware } from './middlewares/error';
import { globalMiddleware } from './middlewares/global';
import { socketMiddleware } from './middlewares/socket';

// dayjs 扩展utc
dayjs.extend(utc);
dayjs.extend(timezone);
dayjs.extend(relativeTime);

const app = new Koa();
const server = createServer(app.callback());

app.use(cross({
  maxAge: 5,
  credentials: true,
  origin: ctx => ctx.header.origin,
  allowMethods: [`GET`, `POST`, `DELETE`, `PUT`, `OPTIONS`],
  exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
  allowHeaders: ['Content-Type', 'Authorization', 'Accept', 'Platform', 'X-Requested-With']
}));

app.use(koaBody());
app.use(dbConnect());
app.use(socketMiddleware(server));

// add routes
for (const route of allRoutes) {
  apiRouter.use(route.routes());
}

app.use(globalMiddleware);
app.use(errorMiddleware);
app.use(apiRouter.routes());

const port = process.env.PORT;
server.listen(port, () => console.log(`server start at ${port}`));